<template>
  <BaseCharts ref="baseChartsRef"
              :options="options"
              :autoRander="autoRander"
              :autoNumber="autoNumber"
              :height="height"
              @legendselectchanged="legendselectchanged">
  </BaseCharts>
</template>

<script setup>
import { nextTick, ref, watch } from "vue";
import { useEchart } from "@/hooks/useEchart.js";
import { fontSize } from "@/utils/rem/rem.js";
import { getChartTootipFormatter } from "@/utils/formatter.js";
import BaseCharts from "@/components/echarts/vpt-base-chart/index.vue";

const props = defineProps({
  chartType: { type: String, default: "init" },
  // 图表数据
  chartData: { type: Array, default: () => [] },
  // chart标题
  chartTitle: { type: String, default: "" },
  // 横坐标数据
  xAxisData: { type: Array, default: () => [] },
  // 图例数据
  legendData: { type: Array, default: () => [] },
  // 分段
  splitNumber: { type: Number, default: 4 },
  // 边距
  grid: { type: Object, default: () => ({}) },
  // 图例配置项
  legendProps: { type: Object, default: () => ({}) },
  // 横坐标间隔数据
  xAxisInterval: { type: [Number, String], default: () => "auto" },
  // y轴相关配置项
  yAxisProps: { type: Object, default: () => ({}) },
  // 折线颜色
  color: { type: Array, default: () => [] },
  // 循环渲染
  autoRander: { type: Boolean, default: false },
  // 循环渲染间隔 单位S
  autoNumber: { type: Number, default: 60 },
  // 标题相关配置
  titleProps: { type: Object, default: () => ({}) },
  // 图表高度
  height: {
    type: String,
    default: () => {
      return "100%";
    },
  },
  // 滚动条样式配置
  dataZoom: { type: Object, default: () => ({}) },
  // x轴标签字号
  xAxisFontSize: { type: Number, default: 14 },
  // y轴标签字号
  yAxisFontSize: { type: Number, default: 14 },
  // 图例文本字号
  legendTextStyleFontSize: { type: Number, default: 12 },
  // 图例间隔
  itemGapFontSize: { type: Number, default: 20 },
  // 展示x轴标签
  showAxisLabel: { type: Boolean, default: true },
  // 平滑状态
  smooth: {
    type: Boolean,
    default: false,
  },
  // xAxisInterval: {
  //   type: Number,
  //   default: 0,
  // },
  // 循环渲染
  autoRander: { type: Boolean, default: true },
  tooltipName: { type: String, default: "" },
});

const baseChartsRef = ref(null);
const fontColor = "#0D1C28";
const options = ref({});

// 使用hooks
useEchart(getOptions);

watch(
  () => ({
    chartData: props.chartData,
    chartType: props.chartType,
    legendData: props.legendData,
    xAxisData: props.xAxisData,
  }),
  () => {
    nextTick(async () => {
      if (props.legendData && props.chartType == "init") {
        legendSelect.value = {};
        legendSelect.value = props.legendData.reduce((acc, item) => {
          acc[item] = true;
          return acc;
        }, {});
      }
      if (props.chartType == "update") {
        updateSeries();
      } else {
        getOptions();
      }
    });
  },
  { deep: true }
);

let legendSelect = ref({});
const legendselectchanged = (event) => {
  legendSelect.value = event.selected;
  updateSeries();
};

function getOptions () {
  options.value = {
    animation: false,
    title: {
      text: props.chartTitle,
      textStyle: {
        color: fontColor,
        fontWeight: 400,
        fontSize: fontSize(28),
      },
      ...props.titleProps,
    },
    tooltip: {
      trigger: "axis",
      textStyle: {
        fontFamily: "HarmonyOS_SansSC_Medium",
      },
      borderColor: "#4895e899",
      extraCssText:
        "background: linear-gradient(180deg, #19406B, rgba(0, 134, 205, 0.91))", //渐变颜色
      appendToBody: true,
      confine: false,
      className: "echart-popover",
      formatter: (item) => {
        if (item[0].seriesName == "series\u00000") {
          return `<div style="display:flex;align-items: center;margin-right: 20px;"><div style="margin-top: 1px;color:#fff">${props.tooltipName}</div><div style="margin-left: 15px;color:#fff">${item[0].value}</div></div>`;
        } else {
          return getChartTootipFormatter(item, {
            titleKey: "axisValueLabel",
            itemKey: "seriesName",
            valueKey: "value",
          });
        }
      },
    },
    grid: {
      left: 0,
      right: 0,
      bottom: 0,
      top: fontSize(20),
      containLabel: true,
      ...props.grid,
    },
    legend: {
      silent: true,
      // selectedMode: false,
      type: "scroll",
      left: 0,
      top: "top",
      bottom: fontSize(0),
      icon: "path://M175.494095 567.929905c-21.26019 0-38.521905-21.845333-38.521905-48.761905 0-26.965333 17.261714-48.761905 38.521905-48.761905H878.689524c21.26019 0 38.521905 21.796571 38.521905 48.761905 0 26.916571-17.261714 48.761905-38.521905 48.761905H175.542857z",
      data: [...props.legendData],
      selected: legendSelect.value,
      textStyle: {
        color: "#fff",
        fontSize: fontSize(12),
        height: fontSize(20),
        lineHeight: fontSize(20),
        fontFamily: "HarmonyOS_SansSC_Medium",
      },
      pageIconColor: "#fff",
      pageIconSize: fontSize(14),
      pageTextStyle: {
        color: "#8893A1",
        fontSize: fontSize(11),
      },
      ...props.legendProps,
    },
    xAxis: {
      type: "category",
      data: props.xAxisData,
      axisLabel: {
        interval: props.xAxisInterval,
        color: fontColor,
        fontSize: fontSize(props.xAxisFontSize),
        fontFamily: "HarmonyOS_SansSC_Medium",
      },
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: {
      splitNumber: props.splitNumber,
      axisLabel: {
        show: true,
        color: fontColor,
        fontWeight: 400,
        interval: 0,
        fontSize: fontSize(props.yAxisFontSize),
        fontFamily: "HarmonyOS_SansSC_Medium",
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
          color: "#E5E5E5",
        },
      },
      ...props.yAxisProps,
    },
    series: [
      {
        data: props.chartData,
        type: "line",
      },
    ],
    dataZoom: {
      show: false,
      height: 10,
      bottom: 0,
      showDetail: false,
      startValue: 0,
      endValue: 10, // 可视窗口下显示的数量, 设置endValue值被当作数据的index取值
      borderWidth: 0,
      handleSize: 0,
      showDataShadow: false,
      brushSelect: false,
      // rangeMode: "value",
      fillerColor: "rgba(255, 255, 255, 0.3)",
      backgroundColor: "#0000001a", //两边未选中的滑动条区域的颜色
      borderColor: "transparent",
      moveHandleSize: 0,
      // zoomLock: true,
      handleStyle: {
        color: "#00000029",
        borderWidth: 0,
      },
      ...props.dataZoom,
    },
  };
}
function arraysEqual (a, b) {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}
async function updateSeries () {
  try {
    const chartInstance = await getEchartsInstance();
    if (chartInstance) {
      const newChartOption = chartInstance.getOption();
      newChartOption.legend[0].data = [...props.legendData];
      newChartOption.xAxis[0].data = props.xAxisData;
      // 遍历 series 更新 data
      (newChartOption.series[0].data = props.chartData),
        (newChartOption.legend[0].selected = legendSelect.value);
      // 更新 series 部分
      chartInstance.setOption(newChartOption, false);
    }
  } catch (error) {
    // console.error("Failed to update chart:", error);
  }
}

function getEchartsInstance () {
  return new Promise((resolve) => {
    baseChartsRef.value.commonFunc((instance) => resolve(instance));
  });
}

defineExpose({
  reloadEchart: () => {
    baseChartsRef.value.reloadEchart();
  },
});
</script>
